/**
 * 数据字典管理通用逻辑 Hook
 *
 * 抽取数据字典的通用业务逻辑
 * 包括字典数据获取、缓存、格式化等功能
 */

import { ref, computed, onMounted, type Ref } from "vue";
import type { WmsDictData, WmsDictType } from "@/components/wms/types";

/**
 * 字典配置接口
 */
interface UseDictOptions {
  /** 字典类型列表 */
  dictTypes?: string[];
  /** 是否立即加载 */
  immediate?: boolean;
  /** 缓存时间(毫秒) */
  cacheTime?: number;
  /** 是否使用本地缓存 */
  useLocalStorage?: boolean;
}

/**
 * 字典Hook返回值
 */
interface UseDictReturn {
  // 状态
  dictData: Ref<Record<string, WmsDictData[]>>;
  loading: Ref<boolean>;

  // 方法
  getDictData: (dictType: string) => WmsDictData[];
  getDictLabel: (dictType: string, value: any) => string;
  getDictValue: (dictType: string, label: string) => any;
  getDictOptions: (dictType: string) => Array<{ label: string; value: any }>;
  loadDict: (dictType: string) => Promise<WmsDictData[]>;
  loadDicts: (dictTypes: string[]) => Promise<void>;
  refreshDict: (dictType: string) => Promise<void>;
  clearCache: (dictType?: string) => void;
  formatDictValue: (
    dictType: string,
    value: any,
    format?: "label" | "badge" | "tag",
  ) => any;
}

/**
 * 数据字典管理通用Hook
 */
export function useDict(options: UseDictOptions = {}): UseDictReturn {
  const {
    dictTypes = [],
    immediate = true,
    cacheTime = 30 * 60 * 1000, // 默认30分钟缓存
    useLocalStorage = true,
  } = options;

  // 状态
  const dictData = ref<Record<string, WmsDictData[]>>({});
  const loading = ref(false);
  const cacheTimestamps = ref<Record<string, number>>({});

  /**
   * 生成缓存键
   */
  const getCacheKey = (dictType: string): string => {
    return `wms_dict_${dictType}`;
  };

  /**
   * 从本地存储获取缓存
   */
  const getFromCache = (dictType: string): WmsDictData[] | null => {
    if (!useLocalStorage) return null;

    try {
      const cacheKey = getCacheKey(dictType);
      const cached = localStorage.getItem(cacheKey);
      const timestamp = localStorage.getItem(`${cacheKey}_timestamp`);

      if (cached && timestamp) {
        const cacheAge = Date.now() - parseInt(timestamp);
        if (cacheAge < cacheTime) {
          return JSON.parse(cached);
        }
      }
    } catch (error) {
      console.warn(`获取字典缓存失败 ${dictType}:`, error);
    }

    return null;
  };

  /**
   * 保存到本地存储缓存
   */
  const saveToCache = (dictType: string, data: WmsDictData[]): void => {
    if (!useLocalStorage) return;

    try {
      const cacheKey = getCacheKey(dictType);
      localStorage.setItem(cacheKey, JSON.stringify(data));
      localStorage.setItem(`${cacheKey}_timestamp`, Date.now().toString());
      cacheTimestamps.value[dictType] = Date.now();
    } catch (error) {
      console.warn(`保存字典缓存失败 ${dictType}:`, error);
    }
  };

  /**
   * 获取字典数据
   */
  const getDictData = (dictType: string): WmsDictData[] => {
    return dictData.value[dictType] || [];
  };

  /**
   * 根据值获取标签
   */
  const getDictLabel = (dictType: string, value: any): string => {
    const data = getDictData(dictType);
    const item = data.find((item) => item.dictValue === String(value));
    return item?.dictLabel || String(value);
  };

  /**
   * 根据标签获取值
   */
  const getDictValue = (dictType: string, label: string): any => {
    const data = getDictData(dictType);
    const item = data.find((item) => item.dictLabel === label);
    return item?.dictValue;
  };

  /**
   * 获取字典选项(用于下拉框等)
   */
  const getDictOptions = (
    dictType: string,
  ): Array<{ label: string; value: any }> => {
    const data = getDictData(dictType);
    return data.map((item) => ({
      label: item.dictLabel,
      value: item.dictValue,
    }));
  };

  /**
   * 加载单个字典
   */
  const loadDict = async (dictType: string): Promise<WmsDictData[]> => {
    // 检查缓存
    const cached = getFromCache(dictType);
    if (cached) {
      dictData.value[dictType] = cached;
      return cached;
    }

    try {
      loading.value = true;

      // 模拟API调用 - 实际项目中替换为真实API
      const response = await fetch(`/api/system/dict/data/type/${dictType}`);
      const result = await response.json();

      const data: WmsDictData[] = result.data || [];

      // 更新状态
      dictData.value[dictType] = data;

      // 保存缓存
      saveToCache(dictType, data);

      return data;
    } catch (error) {
      console.error(`加载字典失败 ${dictType}:`, error);
      return [];
    } finally {
      loading.value = false;
    }
  };

  /**
   * 批量加载字典
   */
  const loadDicts = async (dictTypes: string[]): Promise<void> => {
    const promises = dictTypes.map((type) => loadDict(type));
    await Promise.all(promises);
  };

  /**
   * 刷新字典(强制重新加载)
   */
  const refreshDict = async (dictType: string): Promise<void> => {
    // 清除缓存
    clearCache(dictType);

    // 重新加载
    await loadDict(dictType);
  };

  /**
   * 清除缓存
   */
  const clearCache = (dictType?: string): void => {
    if (dictType) {
      // 清除指定字典缓存
      delete dictData.value[dictType];
      delete cacheTimestamps.value[dictType];

      if (useLocalStorage) {
        const cacheKey = getCacheKey(dictType);
        localStorage.removeItem(cacheKey);
        localStorage.removeItem(`${cacheKey}_timestamp`);
      }
    } else {
      // 清除所有字典缓存
      dictData.value = {};
      cacheTimestamps.value = {};

      if (useLocalStorage) {
        Object.keys(localStorage).forEach((key) => {
          if (key.startsWith("wms_dict_")) {
            localStorage.removeItem(key);
          }
        });
      }
    }
  };

  /**
   * 格式化字典值
   */
  const formatDictValue = (
    dictType: string,
    value: any,
    format: "label" | "badge" | "tag" = "label",
  ): any => {
    const data = getDictData(dictType);
    const item = data.find((item) => item.dictValue === String(value));

    if (!item) return String(value);

    switch (format) {
      case "label":
        return item.dictLabel;

      case "badge":
        return {
          label: item.dictLabel,
          type: item.cssClass || "info",
          style: item.listClass || "",
        };

      case "tag":
        return {
          label: item.dictLabel,
          color: item.cssClass || "default",
          effect: "light",
        };

      default:
        return item.dictLabel;
    }
  };

  // 生命周期
  if (immediate && dictTypes.length > 0) {
    onMounted(() => {
      loadDicts(dictTypes);
    });
  }

  return {
    // 状态
    dictData,
    loading,

    // 方法
    getDictData,
    getDictLabel,
    getDictValue,
    getDictOptions,
    loadDict,
    loadDicts,
    refreshDict,
    clearCache,
    formatDictValue,
  };
}

/**
 * WMS常用字典类型
 */
export const WMS_DICT_TYPES = {
  // 通用状态
  COMMON_STATUS: "common_status",
  YES_NO: "yes_no",

  // 商品相关
  ITEM_STATUS: "item_status",
  ITEM_CATEGORY: "item_category",
  ITEM_UNIT: "item_unit",

  // 仓库相关
  WAREHOUSE_TYPE: "warehouse_type",
  WAREHOUSE_STATUS: "warehouse_status",

  // 库区相关
  AREA_TYPE: "area_type",
  AREA_STATUS: "area_status",

  // 订单相关
  ORDER_STATUS: "order_status",
  ORDER_TYPE: "order_type",
  ORDER_PRIORITY: "order_priority",

  // 库存相关
  INVENTORY_STATUS: "inventory_status",
  INVENTORY_TYPE: "inventory_type",

  // 操作相关
  OPERATION_TYPE: "operation_type",
  AUDIT_STATUS: "audit_status",
} as const;

/**
 * 创建预配置的字典Hook
 */
export function useWmsDict() {
  return useDict({
    dictTypes: Object.values(WMS_DICT_TYPES),
    immediate: true,
    cacheTime: 60 * 60 * 1000, // 1小时缓存
    useLocalStorage: true,
  });
}

/**
 * 创建状态字典Hook
 */
export function useStatusDict() {
  const { getDictData, getDictLabel, formatDictValue } = useDict({
    dictTypes: [WMS_DICT_TYPES.COMMON_STATUS, WMS_DICT_TYPES.YES_NO],
    immediate: true,
  });

  /**
   * 获取状态标签
   */
  const getStatusLabel = (status: any): string => {
    return getDictLabel(WMS_DICT_TYPES.COMMON_STATUS, status);
  };

  /**
   * 获取状态标签样式
   */
  const getStatusBadge = (status: any) => {
    return formatDictValue(WMS_DICT_TYPES.COMMON_STATUS, status, "badge");
  };

  /**
   * 获取是否标签
   */
  const getYesNoLabel = (value: any): string => {
    return getDictLabel(WMS_DICT_TYPES.YES_NO, value);
  };

  return {
    getStatusLabel,
    getStatusBadge,
    getYesNoLabel,
  };
}
